package com.clementheliou.cheliou.dal.dao.member.impl;

import org.hibernate.Query;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.clementheliou.cheliou.dal.dao.generic.impl.GenericHibernateDAO;
import com.clementheliou.cheliou.dal.dao.member.MemberDAO;
import com.clementheliou.cheliou.dal.dao.member.exception.EMailAlreadyUsedConstraintViolationException;
import com.clementheliou.cheliou.dal.model.member.Member;

/**
 * Hibernate-based implementation of the DAO dedicated to the {@link Member} entities.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link GenericHibernateDAO};
 * @see {@link MemberDAO};
 * @see {@link Member};
 * @see {@link Repository}.
 * @since 1.0
 */
@Repository
public class MemberHibernateDAO extends GenericHibernateDAO<Member> implements MemberDAO {

	/**
	 * Logger for this class.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link Logger};
	 * @see {@link LoggerFactory}.
	 * @since 1.0
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(MemberHibernateDAO.class);

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public Member getMemberFromEMail(String email) {
		LOGGER.debug("Get member from email {}.", email);
		final StringBuilder queryBuilder = new StringBuilder("FROM ").append(Member.class.getName());
		queryBuilder.append(" WHERE email = :email");

		final Query query = getCurrentSession().createQuery(queryBuilder.toString());
		query.setParameter("email", email);

		return (Member) query.uniqueResult();
	}

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public void saveMember(Member memberToSave) throws EMailAlreadyUsedConstraintViolationException {
		try {
			saveEntity(memberToSave);
			flushSession();
		} catch (ConstraintViolationException e) {
			throw new EMailAlreadyUsedConstraintViolationException();
		}
	}
}
